<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-row :gutter="20">
          <!-- 搜索框 -->
          <el-col class="col-item" :span="8">
            <el-input placeholder="请输入内容" v-model="query" class="input-with-select">
              <el-button @click="seachUser" slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </el-col>
          <!-- 添加用户 -->
          <el-col class="col-item" :span="5">
            <el-button type="primary" @click="adduser = true">添加用户</el-button>
          </el-col>
        </el-row>
      </div>
      <!-- 表格区域 -->
      <el-table :data="userlist" border size="medium" stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column prop="roles" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-switch v-model="scope.row.ischecked">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :enterable="false" content="修改角色" placement="top">
              <el-button size="mini" @click="fix_user(scope.row)" type="primary" icon="el-icon-edit"></el-button>
            </el-tooltip>
            <el-tooltip placement="top" :enterable="false" class="item" effect="dark">
              <el-button size="mini" type="danger" icon="el-icon-share"></el-button>
            </el-tooltip>
            <el-tooltip placement="top" :enterable="false" class="item" effect="dark" content="删除角色">
              <el-button size="mini" @click="delitem(scope.row.id)" type="warning" icon="el-icon-delete"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagenum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog  title="添加用户" :visible.sync="adduser" width="45%" @close="Change_close">
      <!-- 添加用户的表单 -->
      <el-form ref="addform" :rules="addrules" :model="addform" label-width="80px">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="addform.username"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input type="password" v-model="addform.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addform.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addform.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 添加用户的表单 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="adduser = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户的对话框 -->
    <el-dialog  title="修改用户" :visible.sync="fixuser" width="45%" @close="fix_close">
      <!-- 修改用户的表单 -->
      <el-form ref="fixform" :rules="addrules" :model="fixform" label-width="80px">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="fixform.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="fixform.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="fixform.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 修改用户的表单 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="adduser = false">取 消</el-button>
        <el-button type="primary" @click="fixForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getuser,adduser,setfix,delroles} from "@/api/login";
export default {
  data(){
    var CheckEmail = (rule, value, callback) => {
      const regEmail = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
      if (regEmail.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法邮箱"));
    };
     var CheckMoblie = (rule, value, callback) => {
      /^[1][3,4,5,7,8][0-9]{9}$/;
      const regMoblie = /^[1][3,4,5,7,8][0-9]{9}$/;
      if (regMoblie.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法手机号"));
    };
    return{
      query:"",
      pagenum:1,
      pagesize:2,
      // 总条数
      total:0,
      // 用户列表
      userlist:[],
      // 添加用户窗口
      adduser:false,
      // 修改用户窗口
      fixuser:false,
      // 添加用户表单信息
      addform:{
        username:"",
        password:"",
        email:"",
        mobile:""
      },
      // 修改用户表单信息
      fixform:{
        username:"",
        email:"",
        mobile:""
      },
      // 添加用户规则
      addrules:{
        username: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: CheckEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: CheckMoblie, trigger: 'blur' }
        ]
      },
      // 选中的用户id
      selectId:""
    }
  },
  created(){
    this.load_data()
  },
  methods:{
    load_data(){
      const{query,pagenum,pagesize}=this
      getuser({query,pagenum,pagesize}).then(({data})=>{
        console.log(data)
        this.userlist=data.data.users
        this.total=data.data.total
      })
    },
    // 每页展示条数改变事件
    handleSizeChange(pagesize){
      // console.log(pagesize)
      this.pagesize=pagesize
      this.load_data()
    },
    // 页码数改变事件
    handleCurrentChange(pagenum){
      // console.log(pagenum)
      this.pagenum=pagenum
      this.load_data()
    },
    // 修改用户前，获取用户信息，并渲染到表单上
    fix_user(data){
      this.fixuser=!this.fixuser
      console.log(data)
      this.fixform=data
      this.selectId=data.id
    },
    // 提交修改请求
    fixForm(){
      const{email,mobile}=this.fixform
      setfix({email,mobile},'users/'+this.selectId).then(({data})=>{
        console.log(data)
        if(data.meta.status==200){
          this.$api.Success(data.meta.msg)
          this.fixuser=false
          this.load_data()
        }
      })
    },
    // 添加用户和表单验证
    submitForm() {
      const{addform}=this
      this.$refs.addform.validate((valid) => {
        console.log(valid)
        if (valid) {
          adduser({username:addform.username,password:addform.password,email:addform.email,mobile:addform.mobile})
          .then(res=>{
            console.log(res)
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 关闭表单后重置表单（添加用户）
    Change_close(){
      this.$refs.addform.resetFields();
    },
    // 关闭表单后重置表单（修改用户）
    fix_close(){
      this.$refs.fixform.resetFields();
    },
    // 删除用户前的提示
    async delitem(id){
      const{userlist,$api:{Success}}=this
       var index=0
       for(let i in userlist){
         if(userlist[i].id==id){
           index=i
         }
       }
      const res = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if(res=="confirm"){
        delroles('users/'+id).then(({data})=>{
          console.log(data)
          if(data.meta.status==200){
            this.$api.Success(data.meta.msg)
            // userlist.splice(index,1)
            this.load_data()
          }
        })
      }
    },
    // 根据关键字搜索用户
    seachUser(){
      this.load_data()
    }
  }
}
</script>
<style Lang="less" scoped>

</style>